# -*- coding: utf-8 -*-
# @Author	: brotherbaby
# @Date		: 2023/11/1 13:55
# @Last Modified by:   brotherbaby
# @Last Modified time: 2023/11/1 13:55
# Thanks for your comments!

import base64
import json
import logging

import requests

from src.config import CONF

logger = logging.getLogger(__name__)

ACCESS_TOKENS = {item["app_id"]: base64.b64encode(item["app_id"].encode()).decode() for item in CONF.app.values()}


def verify_token(p_access_token, client_type):
    app_id = CONF.app[client_type]["app_id"]
    access_token = ACCESS_TOKENS[app_id]
    return p_access_token == access_token


def get_memory_token(client_type):
    app_id = CONF.app[client_type]["app_id"]
    return ACCESS_TOKENS[app_id]


def get_weixin_token(client_type):
    milangze_conf = CONF.app[client_type]
    app_id = milangze_conf["app_id"]
    req_url = CONF.interfaces.get(
        "weixin_url") + f"/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={milangze_conf.get('app_secret')}"
    res = requests.get(req_url)
    if res.status_code != 200:
        logger.error("get weixin access_token failed with error: %s", str(res))
        return None
    res_data = json.loads(res.text)
    global ACCESS_TOKENS
    ACCESS_TOKENS[app_id] = res_data.get("access_token")
    return res_data.get("access_token")
